using System.Linq;
using SFMLStart.Utilities;
using TimeDRODPOF.TDComponents;
using TimeDRODPOF.TDLib;
using TimeDRODPOF.TDPathfinding;
using VeeTileEngine2012;

namespace TimeDRODPOF.TDGame
{
    public class TDGInstance
    {
        private readonly TDGGame _game;

        public TDGInstance(TDGGame mGame)
        {
            _game = mGame;
            Field = new Field();
        }

        public TDPPathfinder Pathfinder { get; private set; }
        public int Width { get { return Field.Width; } }
        public int Height { get { return Field.Height; } }
        public Field Field { get; private set; }

        public void Initialize()
        {
            Field.OnEntityAdded += _game.AddRenderEntity;
            Field.TurnActions[TDLTurnActions.EndChecks] += _game.TurnCheckPlayerKilled;
            Field.TurnActions[TDLTurnActions.EndChecks] += _game.TurnCheckRoomClear;

            Pathfinder = new TDPPathfinder(Field);
            Pathfinder.CreatePathmap(TDLPathmaps.SideGood);
            Pathfinder.CreatePathmap(TDLPathmaps.SideBad);
            Pathfinder.GetPathmap(TDLPathmaps.SideGood).CalculatePathmap();
            Pathfinder.GetPathmap(TDLPathmaps.SideBad).CalculatePathmap();
        }
        public void RunLoadChecks()
        {
            Field.OnLoad.SafeInvoke();
            Field.OnLoadChecks.SafeInvoke();
        }

        public void CreatePlayer(int mX, int mY, int mDirection, bool mSheated = false)
        {
            TDLFactory.Tile = Field.GetTile(mX, mY);
            var result = TDLFactory.Player(mDirection);
            result.GetComponent<TDCMovement>().OnMovedOutsideBounds += (x, y) => _game.RoomSwitchMovement(result, x, y);
            result.GetComponent<TDCWielder>().IsSheated = mSheated;
            Field.AddEntity(result);
        }

        public bool IsClear() { return !Field.GetEntitiesByTag(TDLTags.RequiredKill).Any(); }
    }
}